from fastapi import FastAPI
from pydantic import BaseModel
from typing import List,Union,Dict,Tuple
app = FastAPI()


class Item(BaseModel):
    name: str
    description: str | None = None
    price: float
    tax: float | None = None
    tags: list = [] #没有声明子元素类型
    #或者
    tags: list[str] = [] #也可以声明，这是新版本用法,set(str)



@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
    results = {"item_id": item_id, "item": item}
    return results


class Item(BaseModel):
    name: str
    description: Union[str, None] = None
    price: float
    tax: Union[float, None] = None
    tags: List[str] = [] #声明了子元素类型，老版本


@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
    results = {"item_id": item_id, "item": item}
    return results



class Image(BaseModel):
    url: str
    name: str


class Item(BaseModel):
    name: str
    description: str | None = None
    price: float
    tax: float | None = None
    tags: set[str] = set()
    image: Image | None = None


@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
    results = {"item_id": item_id, "item": item}
    return results
"""
期待这样的
{
    "name": "Foo",
    "description": "The pretender",
    "price": 42.0,
    "tax": 3.2,
    "tags": ["rock", "metal", "bar"],
    "image": {
        "url": "http://example.com/baz.jpg",
        "name": "The Foo live"
    }
}
"""
# 特殊的类型和校验
from fastapi import FastAPI
from pydantic import BaseModel, HttpUrl

app = FastAPI()


class Image(BaseModel):
    url: HttpUrl #该字符串将被检查是否为有效的 URL，并在 JSON Schema / OpenAPI 文档中进行记录。
    name: str


class Item(BaseModel):
    name: str
    description: str | None = None
    price: float
    tax: float | None = None
    tags: set[str] = set()
    image: Image | None = None


@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
    results = {"item_id": item_id, "item": item}
    return results
#还可以将 Pydantic 模型用作 list、set 等的子类型
#例如 image:list[Image] | None = None
#任意嵌套深度

"""
任意Dict组成的请求体
"""
from fastapi import FastAPI

app = FastAPI()
@app.post("/index-weights/")
async def create_index_weights(weights: dict[int, float]): #任意键为 int 类型并且值为 float 类型的 dict
    return weights
"""请记住 JSON 仅支持将 str 作为键。

但是 Pydantic 具有自动转换数据的功能。

这意味着，即使你的 API 客户端只能将字符串作为键发送，只要这些字符串内容仅包含整数，Pydantic 就会对其进行转换并校验。

然后你接收的名为 weights 的 dict 实际上将具有 int 类型的键和 float 类型的值。"""

